<template>
	<view class="order-details" v-if="detailsData.orderId">
		<!-- 头部的背景颜色 -->
		<view class="header"></view>
		<!-- 按钮 -->
		<view class="fixed-btn" v-if="detailsData.orderState == 1">
			<view class="cancel" @click="handleShowCancelOrder">取消订单</view>
			<view class="submit" @click="handlePay">立即支付</view>
		</view>
		<view class="fixed-btn" v-if="detailsData.orderState == 3">
			<view class="sure-shopping" @click="handleSureShopping">确认收货</view>
		</view>

		<view>
			<view :style="heightNav" style="position: relative;">
				<view @click="handleBack" class="back" :style="comBack">
					<u-icon name="arrow-left" size="22" color="#FFFFFF"></u-icon>
				</view>
			</view>
			<view class="row-1" v-if="detailsData.orderState == 1">
				<view class="icon-text">
					<image class="image" src="/static/culturalCreativity/icon-orgin-1.png" mode="aspectFill">
					</image>
					<view class="text">待付款</view>
				</view>
				<view class="time">
					<u-count-down :time="comTimes" format="DD:HH:mm:ss" millisecond @change="onChange"
						@finish.once="handleFinish" ref="count-down" :autoStart="false">
						<view>
							剩余{{ timeData.minutes || 0 }}&nbsp;分{{ timeData.seconds || 0 }}&nbsp;秒自动取消订单
						</view>
					</u-count-down>
				</view>
				<view class="btn" @click="handlePay">立即付款</view>
			</view>

			<view class="row-1" v-if="detailsData.orderState == 2">
				<view class="icon-text">
					<image class="image" src="/static/culturalCreativity/icon-orgin-2.png" mode="aspectFill">
					</image>
					<view class="text">待发货</view>
				</view>
				<view class="time">买家已付款，商家将尽快发货</view>
				<view class="btn" @click="handleTx">提醒发货</view>
			</view>

			<view class="row-1" v-if="detailsData.orderState == 3">
				<view class="icon-text">
					<image class="image" src="/static/culturalCreativity/icon-orgin-3.png" mode="aspectFill">
					</image>
					<view class="text">待收货</view>
				</view>
				<view class="time">商品已发货，请静待送货上门</view>
			</view>

			<view class="row-1" v-if="detailsData.orderState == 5 && detailsData.orderState == 4">
				<view class="icon-text">
					<image class="image" src="/static/culturalCreativity/icon-orgin-5.png" mode="aspectFill">
					</image>
					<view class="text">订单已完成</view>
				</view>
				<view class="time">商品已成功送达</view>
			</view>
			<view class="row-1" v-if="detailsData.orderState == 6">
				<view class="icon-text">
					<image class="image" src="/static/culturalCreativity/icon-orgin-5.png" mode="aspectFill">
					</image>
					<view class="text">订单已取消</view>
				</view>
				<view class="time">商品订单已成功取消</view>
			</view>

			<view class="box">
				<view class="row-2">
					<!-- 物流信息 -->
					<view class="item" v-if="[3,4,5,8].some(item=>item==detailsData.orderState)"
						@click="handleLogistics">
						<image class="image" src="/static/culturalCreativity/icon-orgin-car.png" mode="aspectFill"
							style="width: 30rpx; height: 26rpx;">
						</image>
						<view class="" style="flex:1;">
							<view class="text">
								<text>{{logisticsData.logisticsName}}</text>
								<view class="arrow-right">
									<u-icon name="arrow-right" size="16" color="black"></u-icon>
								</view>
							</view>
							<view class="address">{{logisticsData.detailsLastData}}</view>
						</view>
					</view>
					<!-- 地址信息 -->
					<view class="item" @click="handleShowAddress">
						<image class="image" src="/static/culturalCreativity/icon-address.png" mode="aspectFill">
						</image>
						<view class="">
							<view class="text">
								<text>{{detailsData.recipientName}}</text>
								<text>{{detailsData.recipientPhone}}</text>
							</view>
							<view class="address">{{comAddress}}</view>
						</view>
					</view>
				</view>

				<view class="row-3">
					<view class="list" :class="showMoreData?'more':''">
						<view class="list-item" v-for="(item,index) in detailsData.wcOrderGoodsList" :key="index">
							<sure-order-list :item="item" res="sure-order-list"></sure-order-list>
							<view class="shopping-btn"
								v-if="detailsData.orderState != 1 && detailsData.orderState != 6">

								<view class="cancel" @click="handleShowCancelMoney(item)"
									v-if="[1,2,3,4,6].some(m=> m ==item.goodsStatus) && detailsData.orderState == 2">
									<text v-if="item.goodsStatus == 1">退款</text>
									<text v-else>{{item.goodsStatus|itemGoodsStatus2}}</text>
								</view>

								<!-- handleCancelShopping -->
								<view class="cancel"
									v-if="[1,2,3,4,6].some(m=> m ==item.goodsStatus) && detailsData.orderState == 3"
									@click="handleServiced(item)">
									<text v-if="item.goodsStatus == 1">退货</text>
									<text v-else>{{item.goodsStatus|itemGoodsStatus3}}</text>
								</view>

								<view class="cancel" v-if="[4,5].some(m=> m ==detailsData.orderState)"
									@click="handleServiced(item)">
									<text v-if="item.goodsStatus==1">退换/售后</text>
									<text v-else>{{item.goodsStatus|itemGoodsStatus3}}</text>
								</view>
								
								<view class="cancel" v-if="item.showPingJia" @click="handlePj(detailsData,item)">评价
								</view>
								<!-- <view class="cancel" v-else>{{item.goodsStatus | goodsStatusFilter}}</view> -->
							</view>
						</view>
					</view>
					<view class="btn" v-if="detailsData.wcOrderGoodsList.length>3" @click="handleShowMoreData">
						<view style="margin-right: 12rpx;">{{showMoreData?'收起':'更多'}}</view>
						<view :class="showMoreData?'more':''">
							<u-icon name="arrow-down" color="#878787" size="12"></u-icon>
						</view>
					</view>
				</view>

				<view class="row-4">
					<view class="item">
						<view class="label">商品总额</view>
						<view class="value">￥{{detailsData.totalPrice || 0}}</view>
					</view>
					<view class="item">
						<view class="label">运费</view>
						<view class="value">￥{{detailsData.freight || 0}}</view>
					</view>
					<view class="item">
						<view class="label">优惠券抵扣</view>
						<view class="value">-￥{{detailsData.couponPrice || 0}}</view>
					</view>
					<view class="price">
						<text>实付金额</text>
						<text style="color: #FD8F19;">￥{{detailsData.actualPayment }}</text>
					</view>
				</view>

				<view class="row-5">
					<view class="item">
						<view class="label">订单编号</view>
						<view class="value">{{detailsData.orderNumber}}</view>
					</view>
					<view class="item">
						<view class="label">下单时间</view>
						<view class="value">{{detailsData.orderTime | timeFilter}}</view>
					</view>
					<view class="item" v-if="detailsData.payTime">
						<view class="label">支付时间</view>
						<view class="value">{{detailsData.payTime | timeFilter}}</view>
					</view>
					<view class="item" v-if="detailsData.payTime">
						<view class="label">支付方式</view>
						<view class="value">微信支付</view>
					</view>
					<view class="item">
						<view class="label">备注</view>
						<view class="value">{{detailsData.buyerRemark || '无'}}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 物流信息 -->
		<shopping-logistics ref="shopping-logistics"></shopping-logistics>
		<reason-for-refund @submit="handleCancelMoney" ref="reason-for-refund1" title="退款原因"></reason-for-refund>
		<reason-for-refund @submit="handleCancel" ref="reason-for-refund2" title="取消订单原因"></reason-for-refund>
		<!-- 地址 -->
		<shopping-details-address @select="handleSelectorAdderss" ref="shopping-details-address" />
		<!-- 评价 -->
		<shopping-comment ref="shopping-comment" @submit="getList"></shopping-comment>
	</view>
</template>
<script>
	import sureOrderList from "../components/sure-order-list.vue";
	import reasonForRefund from "../components/reason-for-refund.vue";
	import shoppingDetailsAddress from "../components/shopping-details-address.vue";
	import shoppingComment from "../components/shopping-comment.vue";
	import {
		findMyOrder,
		updateMyOrder,
		refuseMyOrder,
		confirmReceiveGoods,
		getSettingData,
		listOrderInfo
	} from "@/culturalCreativity/http/my.js";
	import {
		realmName
	} from "@/http";
	import {
		dateFormat
	} from "@/utils/pay.js";
	import {
		payWcOrder,
		listLogistics
	} from "@/culturalCreativity/http/common.js";
	import shoppingLogistics from "../components/shopping-logistics.vue";
	export default {
		components: {
			sureOrderList,
			shoppingLogistics,
			reasonForRefund,
			shoppingDetailsAddress,
			shoppingComment
		},
		data() {
			return {
				id: null,
				detailsData: {},
				logisticsData: {},
				timeData: null,
				showMoreData: false,
				comTimes: 1
			}
		},
		onShow(){
			setTimeout(()=>{
				if(this.id){
					this.getList();
				}
			},50)
		},
		async onLoad({
			id
		}) {
			this.id = id;
		},
		methods: {
			async getList() {
				let res = await findMyOrder(this.id);
				let detailsData = res.data.data;
				detailsData.wcOrderGoodsList = detailsData.wcOrderGoodsList.map(item => {
					return {
						...item,
						goodsPicAddress: item.goodsPic,
						shoppingNumber: item.num,
						mealCardPay: item.paidInAmount
					}
				});
				this.detailsData = detailsData;
				this.getSetting(); //倒计时加载
				this.getComment(); //订单评价
				if ([3, 4, 5, 8].some(item => item == detailsData.orderState)) { // 物流信息
					let res2 = await listLogistics(detailsData.orderNumber);
					if (!(res2.data.data && res2.data.data.details)) return;
					let details = JSON.parse(res2.data.data.details)
					this.logisticsData = {
						...res2.data.data,
						detailsLastData: details[details.length - 1].accept_station
					};
				};
			},
			async getComment() {
				if (this.detailsData.orderState != 4) return;
				console.log("评价列表");
				let res = await listOrderInfo({
					orderId: this.id
				});
				this.detailsData.wcOrderGoodsList = this.detailsData.wcOrderGoodsList.map((item) => {
					if (res.data.data.resultList.some(i => i.goodsId == item.goodsId)) {
						item.showPingJia = true;
					};
					return item;
				});
			},
			handleServiced(options) { //退换售后
				uni.setStorageSync('PAGE_DATA', options);
				if (options.goodsStatus == 1) {
					uni.navigateTo({
						url: "/culturalCreativity/common/afterSalesSelectorType"
					});
				}else{
					uni.navigateTo({
						url: "/culturalCreativity/common/afterSalesDetails"
					});
				}
				
			},
			async getSetting() {
				if (this.detailsData.orderState != 1) return;
				let res = await getSettingData();
				let date = new Date(this.detailsData.orderTime);
				date.setMinutes(date.getMinutes() + Number(res.data.data.cancleTime));
				if (date.getTime() - Date.now() <= 0) return this.handleFinish(); //已过期
				this.comTimes = this.detailsData.orderTime ? date.getTime() - Date.now() : 0;
				this.$nextTick(() => {
					setTimeout(() => {
						this.$refs['count-down'].start();
					}, 300);
				})
			},
			handleShowMoreData() {
				this.showMoreData = !this.showMoreData
			},
			async handleCancelShopping(options) {
				if (options.goodsStatus != 1) return;
				uni.showLoading({
					title: "正在退货",
					mask: true
				});
				let res = await refuseMyOrder([{
					orderGoodsNumber: options.orderGoodsNumber,
					refuseReason: ""
				}]);
				this.getList();
				console.log("退货", options);
			},
			handleShowCancelMoney(options) { //打开退款原因
				if (options.goodsStatus != 1) return;
				this.$refs['reason-for-refund1'].init(options);
			},
			handleShowCancelOrder() { //打开取消订单原因
				this.$refs['reason-for-refund2'].init(this.detailsData);
			},
			async handleCancelMoney(options) { //申请退款
				uni.showLoading({
					title: "正在退款",
					mask: true
				});
				let res = await refuseMyOrder([{
					orderGoodsNumber: options.orderGoodsNumber,
					refuseReason: options.refuseReason
				}]);
				this.getList();
			},
			async handleSureShopping() { //确认收货
				try {
					uni.showLoading({
						title: "正在确认...",
						mask: true
					});
					let res = await confirmReceiveGoods(this.detailsData.orderId);
					uni.showToast({
						title: "确认成功",
						icon: "success"
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 500)
				} catch (e) {
					uni.hideLoading();
					console.error(e);
				}
			},
			handleLogistics() {
				this.$refs['shopping-logistics'].init(this.detailsData.orderNumber)
			},
			handleTx() {
				uni.showToast({
					title: "提醒成功",
					icon: "success"
				})
			},
			handleBack() { //返回上一页
				uni.navigateBack();
			},
			onChange(e) {
				this.timeData = e
			},
			async handleCancel() { //取消订单
				uni.showLoading({
					title: "正在取消..."
				})
				let res = await updateMyOrder({
					orderId: this.detailsData.orderId,
					orderNumber: this.detailsData.orderNumber,
					orderState: 6, //取消订单
				});
				uni.showToast({
					title: "取消成功",
					icon: "success"
				});
				setTimeout(() => {
					this.handleBack();
				}, 500);
			},
			async handlePay(options) { //支付
				uni.setStorageSync("msg_data", {
					totalAmount: this.detailsData.actualPayment,
					orderId: this.detailsData.orderNumber,
					fileName: "culturalCreativity"
				});
				uni.navigateTo({
					url: "/commonPages/pay/index"
				});
			},
			async handleFinish() {
				try {
					uni.showToast({
						title: "支付已过期",
						mask: true,
						icon: "error",
						duration: 99999
					});
					setTimeout(async () => {
						await updateMyOrder({
							orderId: this.detailsData.orderId,
							orderNumber: this.detailsData.orderNumber,
							orderState: 6, //取消订单
						});
						uni.navigateBack();
						uni.hideLoading();
					}, 1500)
				} catch (e) {
					console.error('报错：', e)
					uni.navigateBack();
					uni.hideLoading();
				}
			},
			handleShowAddress() {
				if (this.detailsData.orderState != 1) return;
				this.$refs["shopping-details-address"].init();
			},
			handlePj(options, item) {
				this.$refs['shopping-comment'].init(options, item);
			},
			async handleSelectorAdderss(e) { //更新地址
				uni.showLoading({
					title: "更换地址...",
					mask: true
				});
				this.detailsData.recipientCity = e.location.split(" ")[0];
				this.detailsData.recipientCounty = e.location.split(" ")[1];
				this.detailsData.recipientProvince = e.location.split(" ")[2];
				this.detailsData.recipientAddress = e.detailedAddress;
				this.detailsData.recipientPhone = e.userPhone;
				this.detailsData.recipientName = e.receiver;
				let res = await updateMyOrder(this.detailsData);
				uni.showToast({
					title: "地址修改成功",
					icon: "success"
				});
			}
		},
		filters: {
			timeFilter(s) {
				if (!s) return ''
				return dateFormat("YYYY-mm-dd HH:MM:SS", new Date(s));
			},
			itemGoodsStatus2(num) {
				switch (Number(num)) {
					case 0:
						return "待付款"
					case 1:
						return "已付款"
					case 2:
						return "已退款"
					case 3:
						return "退款中"
					case 4:
						return "退款失败"
					case 5:
						return "已取消"
					case 6:
						return "退款审核中"
					case 7:
						return "拒绝退货"
					default:
						return "error"
				}
			},
			itemGoodsStatus3(num) {
				switch (Number(num)) {
					case 0:
						return "待付款"
					case 1:
						return "已付款"
					case 2:
						return "已退款"
					case 3:
						return "退货中"
					case 4:
						return "退货失败"
					case 5:
						return "已取消"
					case 6:
						return "退货审核中"
					case 7:
						return "拒绝退货"
					default:
						return "error"
				}
			}
		},
		computed: {
			comAddress() {
				if (!this.detailsData.recipientAddress) return '';
				let {
					recipientCity,
					recipientCounty,
					recipientProvince,
					recipientAddress
				} = this.detailsData;
				return `${recipientCity} ${recipientCounty} ${recipientProvince} ${recipientAddress}`;
			},
			comBack() {
				let res = wx.getMenuButtonBoundingClientRect();
				return `top:${res.top}px;height:${res.height}px;`;
			},
			heightNav() {
				let res = wx.getMenuButtonBoundingClientRect();
				return `height:${res.height}px;padding-top:${res.top}px;`;
			}
		}
	}
</script>
<style lang="scss" scoped>
	.order-details {
		position: relative;
	}

	.header {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		z-index: -1;
		height: 500rpx;
		background: linear-gradient(180deg, #FD8F19 0%, #FFC236 100%);
		display: flex;
		justify-content: flex-start;
		box-sizing: border-box;
	}

	.back {
		position: absolute;
		left: 30rpx;
		display: flex;
		align-items: center;
	}

	.fixed-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding-top: 10rpx;
		padding-bottom: calc(38rpx + env(safe-area-inset-bottom));
		display: flex;
		justify-content: center;
		box-shadow: 0rpx -10rpx 10rpx 0rpx rgba(0, 0, 0, 0.05);
		z-index: 1;
		background-color: #FFFFFF;

		.sure-shopping {
			width: 682rpx;
			height: 76rpx;
			line-height: 76rpx;
			text-align: center;
			border-radius: 40rpx;
			border: 2rpx solid #BDBDBD;
			font-size: 32rpx;
			font-weight: 400;
			color: #1F1F1F;
		}

		.cancel,
		.submit {
			border: 1px solid #BDBDBD;
			width: 332rpx;
			height: 76rpx;
			line-height: 76rpx;
			text-align: center;
			border-radius: 40rpx;
			font-size: 32rpx;
			color: #1F1F1F;
		}

		.submit {
			margin-left: 14rpx;
			background-color: #FD8F19;
			border-color: #FD8F19;
			color: #FFFFFF;
		}
	}

	.row-5 {
		margin-top: 24rpx;
		background: #FFFFFF;
		border-radius: 30rpx;
		padding: 32rpx;

		.item {
			font-size: 28rpx;
			color: #2E2F31;
			display: flex;

			&+.item {
				margin-top: 24rpx;
			}

			.label {
				color: #999999;
				width: 144rpx;
			}
		}
	}

	.row-4 {
		background: #FFFFFF;
		border-radius: 30rpx;
		padding: 32rpx;
		margin-top: 24rpx;

		.item {
			color: #1F1F1F;
			font-size: 28rpx;
			display: flex;
			justify-content: space-between;
			align-items: flex-end;
			margin-bottom: 24rpx;
		}

		.price {
			display: flex;
			justify-content: flex-end;
			align-items: flex-end;
			color: #2E2F31;
			font-size: 28rpx;
			font-weight: 500;
		}
	}

	.row-3 {
		background: #FFFFFF;
		border-radius: 30rpx;
		margin-top: 24rpx;
		padding: 32rpx;

		.list {
			max-height: 710rpx;
			overflow: hidden;
		}

		.list.more {
			max-height: none;
		}

		.list-item+.list-item {
			margin-top: 24rpx;
		}

		.shopping-btn {
			display: flex;
			justify-content: flex-end;

			.cancel {
				min-width: 156rpx;
				height: 56rpx;
				border-radius: 40rpx;
				border: 2rpx solid #BDBDBD;
				line-height: 56rpx;
				text-align: center;
				font-size: 28rpx;
				padding: 0 8rpx;
				color: #1F1F1F;

				&+.cancel {
					margin-left: 12rpx;
				}
			}
		}

		.btn {
			padding-top: 50rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #878787;
			font-size: 24rpx;

			.more {
				transform: rotate(180deg);
			}
		}
	}

	.box {
		margin-top: 40rpx;
		border-radius: 30rpx 30rpx 0 0;
		background-color: #F7F7F7;
		padding-bottom: calc(200rpx + env(safe-area-inset-bottom));
	}

	.row-2 {
		border-radius: 30rpx;
		background: #FFFFFF;
		padding: 0 32rpx;

		.item {
			display: flex;
			align-items: center;
			padding: 32rpx 0;

			&+.item {
				border-top: 1px solid #EEEEEE;
			}

			.image {
				width: 30rpx;
				height: 35rpx;
				margin-right: 24rpx;
			}

			.text {
				position: relative;
				font-size: 28rpx;
				font-weight: 400;
				color: #1F1F1F;

				.arrow-right {
					position: absolute;
					top: 50%;
					right: 0;
					transform: translate(0, -50%);
				}
			}

			.address {
				margin-top: 4rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #878787;

				white-space: nowrap;
				word-break: break-all;
				text-overflow: ellipsis;
				overflow: hidden;
				width: 620rpx;
			}
		}
	}

	.row-1 {
		display: flex;
		flex-direction: column;
		padding-top: 36rpx;
		align-items: center;

		.icon-text {
			display: flex;
			align-items: center;
			justify-content: center;

			.image {
				width: 34rpx;
				height: 36rpx;
				margin-right: 12rpx;
			}

			.text {
				font-size: 38rpx;
				font-weight: 500;
				color: #FFFFFF;
			}
		}

		.time {
			margin: 12rpx 0 24rpx 0;
			font-size: 22rpx;
			font-weight: 400;
			color: #FFFFFF;
		}

		.btn {
			width: 256rpx;
			height: 66rpx;
			text-align: center;
			line-height: 66rpx;
			background: #FFFFFF;
			border-radius: 33rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #FD8F19;
		}
	}
</style>
